package com.cskaoyan.controller;

import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.data.CommentListData;
import com.cskaoyan.bean.data.CountCommentData;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.domain.MarketComment;
import com.cskaoyan.domain.MarketUser;
import com.cskaoyan.service.MarketCommentService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("wx/comment")
public class WxCommentController {
    @Autowired
    MarketCommentService commentService;

    @RequestMapping("list")
    public BaseRespVo list(Integer valueId, Byte type, Integer limit, Integer page, Boolean showType) {

        List<CommentListData> commentsList = commentService.queryCommentsByValueIdAndType(valueId, type, showType);

        CommonData data = new CommonData();
        data.setLimit(limit);
        data.setList(commentsList);
        data.setPage(page);
        int total = (int) commentsList.stream().count();
        data.setTotal(total);
        int pages = total % limit == 0 ? total / limit : total / limit + 1;
        data.setPages(pages);
        return BaseRespVo.ok(data);

    }

    @RequestMapping("count")
    public BaseRespVo count(Integer valueId, Byte type) {
        CountCommentData commentData = commentService.countImageOrNoImage(valueId, type);

        return BaseRespVo.ok(commentData);

    }

    @RequestMapping("post")
    public BaseRespVo post(@RequestBody Map map) {
        Subject subject = SecurityUtils.getSubject();
        Integer userId = null;

        if (subject.isAuthenticated()) {
            MarketUser principal = (MarketUser) subject.getPrincipal();
            userId = principal.getId();
        }

        commentService.updateTopicComment(map, userId);

        Integer valueId = Integer.valueOf(map.get("valueId").toString());
        List<MarketComment> marketComments = commentService.selectCommentByValueId(valueId);
        return BaseRespVo.ok(marketComments);

    }
}
